<!doctype html><html><head><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1"><meta name=robots content="noodp"><meta http-equiv=x-ua-compatible content="IE=edge, chrome=1"><title>Java日期问题汇总 - Yulin Lewis' Blog</title><meta name=keywords content="雨临Lewis,Java,hugo,hexo,博客"><meta name=Description content="不想当写手的码农不是好咸鱼_(xз」∠)_"><meta property="og:title" content="Java日期问题汇总"><meta property="og:description" content="日期格式化的跨年问题
通常格式化日期时，都是使用的YYYY/MM/dd来格式化日期，但是在遇到跨年日期时，就会遇到很神奇的现象，如下：


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11


final Calendar calendar = Calendar.getInstance();
// 2020-12-26
calendar.set(2020, 11, 26);
final Date date1226 = calendar.getTime();
// 2020-12-27
calendar.set(2020, 11, 27);
final Date date1227 = calendar.getTime();
// YYYY
final DateFormat Y = new SimpleDateFormat(&#34;YYYY/MM/dd&#34;);
System.out.println(&#34;2020-12-26用YYYY/MM/dd表示:&#34; + Y.format(date1226));
System.out.println(&#34;2020-12-27用YYYY/MM/dd表示:&#34; + Y.format(date1227));"><meta property="og:type" content="article"><meta property="og:url" content="https://lewky.cn/posts/java-date-issues.html/"><meta property="og:image" content="https://lewky.cn/logo.png"><meta property="article:published_time" content="2021-01-25T23:43:02+08:00"><meta property="article:modified_time" content="2021-10-11T23:43:02+08:00"><meta name=twitter:card content="summary_large_image"><meta name=twitter:image content="https://lewky.cn/logo.png"><meta name=twitter:title content="Java日期问题汇总"><meta name=twitter:description content="日期格式化的跨年问题
通常格式化日期时，都是使用的YYYY/MM/dd来格式化日期，但是在遇到跨年日期时，就会遇到很神奇的现象，如下：


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11


final Calendar calendar = Calendar.getInstance();
// 2020-12-26
calendar.set(2020, 11, 26);
final Date date1226 = calendar.getTime();
// 2020-12-27
calendar.set(2020, 11, 27);
final Date date1227 = calendar.getTime();
// YYYY
final DateFormat Y = new SimpleDateFormat(&#34;YYYY/MM/dd&#34;);
System.out.println(&#34;2020-12-26用YYYY/MM/dd表示:&#34; + Y.format(date1226));
System.out.println(&#34;2020-12-27用YYYY/MM/dd表示:&#34; + Y.format(date1227));"><meta name=application-name content="雨临Lewis的博客"><meta name=apple-mobile-web-app-title content="雨临Lewis的博客"><meta name=theme-color content="#ffffff"><meta name=msapplication-TileColor content="#da532c"><link rel="shortcut icon" type=image/x-icon href=/favicon.ico><link rel=icon type=image/png sizes=32x32 href=/favicon-32x32.png><link rel=icon type=image/png sizes=16x16 href=/favicon-16x16.png><link rel=apple-touch-icon sizes=180x180 href=/apple-touch-icon.png><link rel=mask-icon href=/safari-pinned-tab.svg color=#5bbad5><link rel=manifest href=/site.webmanifest><link rel=canonical href=https://lewky.cn/posts/java-date-issues.html/><link rel=prev href=https://lewky.cn/friends/><link rel=next href=https://lewky.cn/posts/remote-desktop-issue.html/><link rel=stylesheet href=https://cdn.jsdelivr.net/npm/normalize.css@8.0.1/normalize.min.css><link rel=stylesheet href=/css/style.min.css><link rel=stylesheet href=https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.13.0/css/all.min.css><link rel=stylesheet href=https://cdn.jsdelivr.net/npm/animate.css@3.7.2/animate.min.css><script type=application/ld+json>{"@context":"http://schema.org","@type":"BlogPosting","headline":"Java日期问题汇总","inLanguage":"","mainEntityOfPage":{"@type":"WebPage","@id":"https:\/\/lewky.cn\/posts\/java-date-issues.html\/"},"genre":"posts","keywords":"Java, 工作记录","wordcount":2846,"url":"https:\/\/lewky.cn\/posts\/java-date-issues.html\/","datePublished":"2021-01-25T23:43:02+08:00","dateModified":"2021-10-11T23:43:02+08:00","license":"This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.","publisher":{"@type":"Organization","name":"雨临Lewis","logo":"https:\/\/lewky.cn\/images\/avatar.jpg"},"author":{"@type":"Person","name":"雨临Lewis"},"description":""}</script></head><body header-desktop=fixed header-mobile=auto><script type=text/javascript>(window.localStorage&&localStorage.getItem('theme')?localStorage.getItem('theme')==='dark':('auto'==='auto'?window.matchMedia('(prefers-color-scheme: dark)').matches:'auto'==='dark'))&&document.body.setAttribute('theme','dark');</script><div id=mask></div><div class=wrapper><header class=desktop id=header-desktop><div class=header-wrapper><a href=https://github.com/lewky class=github-corner target=_blank title="Follow me on GitHub" aria-label="Follow me on GitHub"><svg width="3.5rem" height="3.5rem" viewBox="0 0 250 250" style="fill:#70b7fd;color:#fff;position:absolute;top:0;border:0;left:0;transform:scale(-1,1)" aria-hidden="true"><path d="M0 0 115 115h15l12 27L250 250V0z"/><path d="M128.3 109C113.8 99.7 119 89.6 119 89.6 122 82.7 120.5 78.6 120.5 78.6 119.2 72 123.4 76.3 123.4 76.3 127.3 80.9 125.5 87.3 125.5 87.3 122.9 97.6 130.6 101.9 134.4 103.2" fill="currentcolor" style="transform-origin:130px 106px" class="octo-arm"/><path d="M115 115C114.9 115.1 118.7 116.5 119.8 115.4L133.7 101.6C136.9 99.2 139.9 98.4 142.2 98.6 133.8 88 127.5 74.4 143.8 58 148.5 53.4 154 51.2 159.7 51 160.3 49.4 163.2 43.6 171.4 40.1 171.4 40.1 176.1 42.5 178.8 56.2 183.1 58.6 187.2 61.8 190.9 65.4 194.5 69 197.7 73.2 200.1 77.6 213.8 80.2 216.3 84.9 216.3 84.9 212.7 93.1 206.9 96 205.4 96.6 205.1 102.4 203 107.8 198.3 112.5 181.9 128.9 168.3 122.5 157.7 114.1 157.9 116.9 156.7 120.9 152.7 124.9L141 136.5C139.8 137.7 141.6 141.9 141.8 141.8z" fill="currentcolor" class="octo-body"/></svg></a><div class=header-title><a href=/ title="Yulin Lewis' Blog"><span class=header-title-pre><i class="fas fa-fw fa-atom"></i></span>雨临Lewis</a></div><div class=menu><div class=menu-inner><div class=dropdown><a href=/posts/ class="menu-item menu-more dropbtn" title=点击查看所有文章><i class="fas fa-fw fa-archive"></i>归档</a><div class="menu-more-content dropdown-content"><a href=/categories/><i class="fas fa-fw fa-th"></i>分类 </a><a href=/tags/><i class="fas fa-fw fa-tag"></i>标签 </a><a href=/hot/ title=文章热度Top15><i class="fas fa-fw fa-fire"></i>热度 </a><a href=/donation/ title=感谢打赏，老板大气~><i class="fas fa-fw fa-donate"></i>打赏 </a><a href=/about/><i class="fas fa-fw fa-at"></i>关于</a></div></div><a class=menu-item href=/friends/ title=欢迎申请友链><i class="fas fa-fw fa-link"></i>友链</a><div class=dropdown><a href=javascript:void(0); class="menu-item menu-more dropbtn" title=一些有意思的东东~><i class="fas fa-fw fa-fan fa-spin"></i>趣味</a><div class="menu-more-content dropdown-content"><a href=/funny/high/ title="前方高能♂ 小心外放！" target=_blank rel=noopener><i class="fas fa-fw fa-dizzy"></i>燥起来！ </a><a href=/funny/mikutap/ title=初音未来音乐游戏 target=_blank rel=noopener><i class="fas fa-fw fa-music"></i>在线打碟 </a><a href=/funny/catch-the-cat/ title=逮住那只猫!><i class="fas fa-fw fa-cat"></i>抓住猫咪</a></div></div><div class=dropdown><a href=/ class="menu-item menu-more dropbtn" title=回到首页><i class="fas fa-fw fa-atom"></i>站点</a><div class="menu-more-content dropdown-content"><a href=/bbs/ title=来留言吧~><i class="fas fa-fw fa-comment"></i>公告留言 </a><a href=https://seo.chinaz.com target=_blank rel=noopener><i class="fas fa-fw fa-chart-line"></i>SEO查询 </a><a href=https://www.ping.cn/http/lewky.cn target=_blank rel=noopener><i class="fas fa-fw fa-bezier-curve"></i>网站测速 </a><a href=/posts/e62c38c4.html/><i class="fas fa-fw fa-cog fa-spin"></i>建站日志</a></div></div><div class=dropdown><a href=javascript:void(0); class="menu-item menu-more dropbtn"><i class="fas fa-fw fa-book"></i>文档</a><div class="menu-more-content dropdown-content"><a href=https://gohugo.io/documentation/ target=_blank rel=noopener><i class="fas fa-fw fa-star"></i>Hugo文档 </a><a href=https://javanote.doc.lewky.cn/ title=尚在完善中~ target=_blank rel=noopener><i class="fab fa-fw fa-java"></i>Java 笔记</a></div></div><a class=menu-item href=/search/ title=渲染搜索结果需要等待几秒钟~><i class="fas fa-fw fa-search"></i>搜索
</a><span class="menu-item delimiter"></span><a href=https://travellings.link target=_blank class=menu-item rel=noopener title=开往-友链接力><i class="fas fa-fw fa-subway"></i></a><a href=https://rssblog.vercel.app/ class=menu-item target=_blank rel=noopener title=RSSBlog><i class="fas fa-fw fa-inbox"></i></a><a href=https://github.com/lewky class=menu-item target=_blank rel=noopener title=GitHub><i class="fab fa-fw fa-github"></i></a></div></div></div></header><header class=mobile id=header-mobile><div class=header-container><div class=header-wrapper><div class=header-title><a href=/ title="Yulin Lewis' Blog"><span class=header-title-pre><i class="fas fa-fw fa-atom"></i></span>雨临Lewis</a></div><div class=menu-toggle id=menu-toggle-mobile><span></span><span></span><span></span></div></div><div class=menu id=menu-mobile><div class=dropdown><a href=/posts/ class="menu-item menu-more dropbtn" title=点击查看所有文章><i class="fas fa-fw fa-archive"></i>归档</a><div class="menu-more-content dropdown-content"><a href=/categories/><i class="fas fa-fw fa-th"></i>分类 </a><a href=/tags/><i class="fas fa-fw fa-tag"></i>标签 </a><a href=/hot/ title=文章热度Top15><i class="fas fa-fw fa-fire"></i>热度 </a><a href=/donation/ title=感谢打赏，老板大气~><i class="fas fa-fw fa-donate"></i>打赏 </a><a href=/about/><i class="fas fa-fw fa-at"></i>关于</a></div></div><a class=menu-item href=/friends/ title=欢迎申请友链><i class="fas fa-fw fa-link"></i>友链</a><div class=dropdown><a href=javascript:void(0); class="menu-item menu-more dropbtn" title=一些有意思的东东~><i class="fas fa-fw fa-fan fa-spin"></i>趣味</a><div class="menu-more-content dropdown-content"><a href=/funny/high/ title="前方高能♂ 小心外放！" target=_blank rel=noopener><i class="fas fa-fw fa-dizzy"></i>燥起来！ </a><a href=/funny/mikutap/ title=初音未来音乐游戏 target=_blank rel=noopener><i class="fas fa-fw fa-music"></i>在线打碟 </a><a href=/funny/catch-the-cat/ title=逮住那只猫!><i class="fas fa-fw fa-cat"></i>抓住猫咪</a></div></div><div class=dropdown><a href=/ class="menu-item menu-more dropbtn" title=回到首页><i class="fas fa-fw fa-atom"></i>站点</a><div class="menu-more-content dropdown-content"><a href=/bbs/ title=来留言吧~><i class="fas fa-fw fa-comment"></i>公告留言 </a><a href=https://seo.chinaz.com target=_blank rel=noopener><i class="fas fa-fw fa-chart-line"></i>SEO查询 </a><a href=https://www.ping.cn/http/lewky.cn target=_blank rel=noopener><i class="fas fa-fw fa-bezier-curve"></i>网站测速 </a><a href=/posts/e62c38c4.html/><i class="fas fa-fw fa-cog fa-spin"></i>建站日志</a></div></div><div class=dropdown><a href=javascript:void(0); class="menu-item menu-more dropbtn"><i class="fas fa-fw fa-book"></i>文档</a><div class="menu-more-content dropdown-content"><a href=https://gohugo.io/documentation/ target=_blank rel=noopener><i class="fas fa-fw fa-star"></i>Hugo文档 </a><a href=https://javanote.doc.lewky.cn/ title=尚在完善中~ target=_blank rel=noopener><i class="fab fa-fw fa-java"></i>Java 笔记</a></div></div><a class=menu-item href=/search/ title=渲染搜索结果需要等待几秒钟~><i class="fas fa-fw fa-search"></i>搜索</a>
<a href=https://travellings.link target=_blank class=menu-item rel=noopener title=开往-友链接力><i class="fas fa-fw fa-subway"></i></a><a href=https://rssblog.vercel.app/ class=menu-item target=_blank rel=noopener title=RSSBlog><i class="fas fa-fw fa-inbox"></i></a><a href=https://github.com/lewky class=menu-item target=_blank rel=noopener title=GitHub><i class="fab fa-fw fa-github"></i></a></div></div></header><div class="search-dropdown desktop"><div id=search-dropdown-desktop></div></div><div class="search-dropdown mobile"><div id=search-dropdown-mobile></div></div><main class=main><div class=container><div class=toc id=toc-auto><h2 class=toc-title>目录</h2><div class=toc-content id=toc-content-auto></div></div><article class="page single"><h1 class="single-title animated flipInX">Java日期问题汇总</h1><div class=post-meta><div class=post-meta-line><span class=post-author><a href=/ title=Author rel=author class=author><i class="fas fa-user-circle fa-fw"></i>雨临Lewis</a></span>&nbsp;<span class=post-category>收录于 <a href=/categories/java/><i class="far fa-folder fa-fw"></i>Java</a></span></div><div class=post-meta-line><i class="far fa-calendar fa-fw"></i>&nbsp;<time datetime=2021-01-25>2021-01-25</time>&nbsp;<i class="far fa-calendar-plus fa-fw"></i>&nbsp;<time datetime=2021-10-11>2021-10-11</time>&nbsp;<i class="fas fa-pencil-alt fa-fw"></i>&nbsp;约 2846 字
<i class="far fa-clock fa-fw"></i>&nbsp;预计阅读 6 分钟&nbsp;<span id=/posts/java-date-issues.html/ class=leancloud_visitors data-flag-title=Java日期问题汇总>
<i class="far fa-eye fa-fw"></i>&nbsp;<span class=leancloud-visitors-count></span>&nbsp;次阅读
</span>&nbsp;
<a href=#comments id=post-meta-vcount title=查看评论><i class="fas fa-comment fa-fw"></i>&nbsp;<span id=/posts/java-date-issues.html/ class=waline-comment-count></span>&nbsp;条评论</a></div></div><div class="details toc" id=toc-static kept><div class="details-summary toc-title"><span>目录</span>
<span><i class="details-icon fas fa-angle-right"></i></span></div><div class="details-content toc-content" id=toc-content-static><nav id=TableOfContents><ol><li><a href=#日期格式化的跨年问题>日期格式化的跨年问题</a></li><li><a href=#日期格式化异常>日期格式化异常</a></li><li><a href=#jdk-8新的日期和时间api>JDK 8新的日期和时间API</a><ol><li><a href=#本地日期api>本地日期API</a></li><li><a href=#时区日期api>时区日期API</a></li><li><a href=#日期和时区的转换>日期和时区的转换</a></li><li><a href=#javasql包下的类和新的日期类的转换><code>java.sql</code>包下的类和新的日期类的转换：</a></li><li><a href=#获取月份年份的最后一天>获取月份、年份的最后一天</a></li><li><a href=#比较两个日期>比较两个日期</a></li></ol></li><li><a href=#参考链接>参考链接</a></li></ol></nav></div></div><div class=content id=content><h2 id=日期格式化的跨年问题>日期格式化的跨年问题</h2><p>通常格式化日期时，都是使用的<code>YYYY/MM/dd</code>来格式化日期，但是在遇到跨年日期时，就会遇到很神奇的现象，如下：</p><div class=highlight><div class=chroma><table class=lntable><tr><td class=lntd><pre class=chroma><code><span class=lnt> 1
</span><span class=lnt> 2
</span><span class=lnt> 3
</span><span class=lnt> 4
</span><span class=lnt> 5
</span><span class=lnt> 6
</span><span class=lnt> 7
</span><span class=lnt> 8
</span><span class=lnt> 9
</span><span class=lnt>10
</span><span class=lnt>11
</span></code></pre></td><td class=lntd><pre class=chroma><code class=language-java data-lang=java><span class=kd>final</span> <span class=n>Calendar</span> <span class=n>calendar</span> <span class=o>=</span> <span class=n>Calendar</span><span class=o>.</span><span class=na>getInstance</span><span class=o>();</span>
<span class=c1>// 2020-12-26
</span><span class=c1></span><span class=n>calendar</span><span class=o>.</span><span class=na>set</span><span class=o>(</span><span class=n>2020</span><span class=o>,</span> <span class=n>11</span><span class=o>,</span> <span class=n>26</span><span class=o>);</span>
<span class=kd>final</span> <span class=n>Date</span> <span class=n>date1226</span> <span class=o>=</span> <span class=n>calendar</span><span class=o>.</span><span class=na>getTime</span><span class=o>();</span>
<span class=c1>// 2020-12-27
</span><span class=c1></span><span class=n>calendar</span><span class=o>.</span><span class=na>set</span><span class=o>(</span><span class=n>2020</span><span class=o>,</span> <span class=n>11</span><span class=o>,</span> <span class=n>27</span><span class=o>);</span>
<span class=kd>final</span> <span class=n>Date</span> <span class=n>date1227</span> <span class=o>=</span> <span class=n>calendar</span><span class=o>.</span><span class=na>getTime</span><span class=o>();</span>
<span class=c1>// YYYY
</span><span class=c1></span><span class=kd>final</span> <span class=n>DateFormat</span> <span class=n>Y</span> <span class=o>=</span> <span class=k>new</span> <span class=n>SimpleDateFormat</span><span class=o>(</span><span class=s>&#34;YYYY/MM/dd&#34;</span><span class=o>);</span>
<span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=s>&#34;2020-12-26用YYYY/MM/dd表示:&#34;</span> <span class=o>+</span> <span class=n>Y</span><span class=o>.</span><span class=na>format</span><span class=o>(</span><span class=n>date1226</span><span class=o>));</span>
<span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=s>&#34;2020-12-27用YYYY/MM/dd表示:&#34;</span> <span class=o>+</span> <span class=n>Y</span><span class=o>.</span><span class=na>format</span><span class=o>(</span><span class=n>date1227</span><span class=o>));</span>
</code></pre></td></tr></table></div></div><p>上述代码输出如下：</p><div class=highlight><div class=chroma><table class=lntable><tr><td class=lntd><pre class=chroma><code><span class=lnt>1
</span><span class=lnt>2
</span></code></pre></td><td class=lntd><pre class=chroma><code class=language-java data-lang=java><span class=n>2020</span><span class=o>-</span><span class=n>12</span><span class=o>-</span><span class=n>26用YYYY</span><span class=o>/</span><span class=n>MM</span><span class=o>/</span><span class=n>dd表示</span><span class=o>:</span><span class=n>2020</span><span class=o>/</span><span class=n>12</span><span class=o>/</span><span class=n>26</span>
<span class=n>2020</span><span class=o>-</span><span class=n>12</span><span class=o>-</span><span class=n>27用YYYY</span><span class=o>/</span><span class=n>MM</span><span class=o>/</span><span class=n>dd表示</span><span class=o>:</span><span class=n>2021</span><span class=o>/</span><span class=n>12</span><span class=o>/</span><span class=n>27</span>
</code></pre></td></tr></table></div></div><p>可以看到，只是一天之差，格式化后却相差了整整一年！这是因为<code>YYYY</code>是基于周最后一天所在年份来格式化年份的，周日是每周第一天。而<code>2020-12-27</code>这天是周日，这一周最后一天属于2021年，于是就发生了上述的神奇现象。下面是官方文档：</p><blockquote><p>Java&rsquo;s DateTimeFormatter pattern &ldquo;YYYY&rdquo; gives you the week-based-year, (by default, ISO-8601 standard) the year of the Thursday of that week.</p></blockquote><p>所以，想要得到正确的结果，需要使用<code>yyyy</code>来替代<code>YYYY</code>，如下：</p><div class=highlight><div class=chroma><table class=lntable><tr><td class=lntd><pre class=chroma><code><span class=lnt> 1
</span><span class=lnt> 2
</span><span class=lnt> 3
</span><span class=lnt> 4
</span><span class=lnt> 5
</span><span class=lnt> 6
</span><span class=lnt> 7
</span><span class=lnt> 8
</span><span class=lnt> 9
</span><span class=lnt>10
</span><span class=lnt>11
</span><span class=lnt>12
</span><span class=lnt>13
</span><span class=lnt>14
</span><span class=lnt>15
</span></code></pre></td><td class=lntd><pre class=chroma><code class=language-java data-lang=java><span class=kd>final</span> <span class=n>Calendar</span> <span class=n>calendar</span> <span class=o>=</span> <span class=n>Calendar</span><span class=o>.</span><span class=na>getInstance</span><span class=o>();</span>
<span class=c1>// 2020-12-26
</span><span class=c1></span><span class=n>calendar</span><span class=o>.</span><span class=na>set</span><span class=o>(</span><span class=n>2020</span><span class=o>,</span> <span class=n>11</span><span class=o>,</span> <span class=n>26</span><span class=o>);</span>
<span class=kd>final</span> <span class=n>Date</span> <span class=n>date1226</span> <span class=o>=</span> <span class=n>calendar</span><span class=o>.</span><span class=na>getTime</span><span class=o>();</span>
<span class=c1>// 2020-12-27
</span><span class=c1></span><span class=n>calendar</span><span class=o>.</span><span class=na>set</span><span class=o>(</span><span class=n>2020</span><span class=o>,</span> <span class=n>11</span><span class=o>,</span> <span class=n>27</span><span class=o>);</span>
<span class=kd>final</span> <span class=n>Date</span> <span class=n>date1227</span> <span class=o>=</span> <span class=n>calendar</span><span class=o>.</span><span class=na>getTime</span><span class=o>();</span>
<span class=c1>// YYYY
</span><span class=c1></span><span class=kd>final</span> <span class=n>DateFormat</span> <span class=n>Y</span> <span class=o>=</span> <span class=k>new</span> <span class=n>SimpleDateFormat</span><span class=o>(</span><span class=s>&#34;YYYY/MM/dd&#34;</span><span class=o>);</span>
<span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=s>&#34;2020-12-26用YYYY/MM/dd表示:&#34;</span> <span class=o>+</span> <span class=n>Y</span><span class=o>.</span><span class=na>format</span><span class=o>(</span><span class=n>date1226</span><span class=o>));</span>
<span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=s>&#34;2020-12-27用YYYY/MM/dd表示:&#34;</span> <span class=o>+</span> <span class=n>Y</span><span class=o>.</span><span class=na>format</span><span class=o>(</span><span class=n>date1227</span><span class=o>));</span>
<span class=c1>// yyyy
</span><span class=c1></span><span class=kd>final</span> <span class=n>DateFormat</span> <span class=n>y</span> <span class=o>=</span> <span class=k>new</span> <span class=n>SimpleDateFormat</span><span class=o>(</span><span class=s>&#34;yyyy/MM/dd&#34;</span><span class=o>);</span>
<span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=s>&#34;2020-12-26用yyyy/MM/dd表示:&#34;</span> <span class=o>+</span> <span class=n>y</span><span class=o>.</span><span class=na>format</span><span class=o>(</span><span class=n>date1226</span><span class=o>));</span>
<span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=s>&#34;2020-12-27用yyyy/MM/dd表示:&#34;</span> <span class=o>+</span> <span class=n>y</span><span class=o>.</span><span class=na>format</span><span class=o>(</span><span class=n>date1227</span><span class=o>));</span>
</code></pre></td></tr></table></div></div><p>结果如下：</p><div class=highlight><div class=chroma><table class=lntable><tr><td class=lntd><pre class=chroma><code><span class=lnt>1
</span><span class=lnt>2
</span><span class=lnt>3
</span><span class=lnt>4
</span></code></pre></td><td class=lntd><pre class=chroma><code class=language-java data-lang=java><span class=n>2020</span><span class=o>-</span><span class=n>12</span><span class=o>-</span><span class=n>26用YYYY</span><span class=o>/</span><span class=n>MM</span><span class=o>/</span><span class=n>dd表示</span><span class=o>:</span><span class=n>2020</span><span class=o>/</span><span class=n>12</span><span class=o>/</span><span class=n>26</span>
<span class=n>2020</span><span class=o>-</span><span class=n>12</span><span class=o>-</span><span class=n>27用YYYY</span><span class=o>/</span><span class=n>MM</span><span class=o>/</span><span class=n>dd表示</span><span class=o>:</span><span class=n>2021</span><span class=o>/</span><span class=n>12</span><span class=o>/</span><span class=n>27</span>
<span class=n>2020</span><span class=o>-</span><span class=n>12</span><span class=o>-</span><span class=n>26用yyyy</span><span class=o>/</span><span class=n>MM</span><span class=o>/</span><span class=n>dd表示</span><span class=o>:</span><span class=n>2020</span><span class=o>/</span><span class=n>12</span><span class=o>/</span><span class=n>26</span>
<span class=n>2020</span><span class=o>-</span><span class=n>12</span><span class=o>-</span><span class=n>27用yyyy</span><span class=o>/</span><span class=n>MM</span><span class=o>/</span><span class=n>dd表示</span><span class=o>:</span><span class=n>2020</span><span class=o>/</span><span class=n>12</span><span class=o>/</span><span class=n>27</span>
</code></pre></td></tr></table></div></div><h2 id=日期格式化异常>日期格式化异常</h2><p>使用新的日期API格式化日期时发生如下异常：</p><div class=highlight><div class=chroma><table class=lntable><tr><td class=lntd><pre class=chroma><code><span class=lnt>1
</span><span class=lnt>2
</span><span class=lnt>3
</span><span class=lnt>4
</span><span class=lnt>5
</span></code></pre></td><td class=lntd><pre class=chroma><code class=language-java data-lang=java><span class=n>java</span><span class=o>.</span><span class=na>time</span><span class=o>.</span><span class=na>DateTimeException</span><span class=o>:</span> <span class=n>Field</span> <span class=n>DayOfYear</span> <span class=n>cannot</span> <span class=n>be</span> <span class=n>printed</span> <span class=n>as</span> <span class=n>the</span> <span class=n>value</span> <span class=n>320</span> <span class=n>exceeds</span> <span class=n>the</span> <span class=n>maximum</span> <span class=n>print</span> <span class=n>width</span> <span class=n>of</span> <span class=n>2</span>
	<span class=n>at</span> <span class=n>java</span><span class=o>.</span><span class=na>time</span><span class=o>.</span><span class=na>format</span><span class=o>.</span><span class=na>DateTimeFormatterBuilder$NumberPrinterParser</span><span class=o>.</span><span class=na>format</span><span class=o>(</span><span class=n>DateTimeFormatterBuilder</span><span class=o>.</span><span class=na>java</span><span class=o>:</span><span class=n>2548</span><span class=o>)</span>
	<span class=n>at</span> <span class=n>java</span><span class=o>.</span><span class=na>time</span><span class=o>.</span><span class=na>format</span><span class=o>.</span><span class=na>DateTimeFormatterBuilder$CompositePrinterParser</span><span class=o>.</span><span class=na>format</span><span class=o>(</span><span class=n>DateTimeFormatterBuilder</span><span class=o>.</span><span class=na>java</span><span class=o>:</span><span class=n>2179</span><span class=o>)</span>
	<span class=n>at</span> <span class=n>java</span><span class=o>.</span><span class=na>time</span><span class=o>.</span><span class=na>format</span><span class=o>.</span><span class=na>DateTimeFormatter</span><span class=o>.</span><span class=na>formatTo</span><span class=o>(</span><span class=n>DateTimeFormatter</span><span class=o>.</span><span class=na>java</span><span class=o>:</span><span class=n>1746</span><span class=o>)</span>
	<span class=n>at</span> <span class=n>java</span><span class=o>.</span><span class=na>time</span><span class=o>.</span><span class=na>format</span><span class=o>.</span><span class=na>DateTimeFormatter</span><span class=o>.</span><span class=na>format</span><span class=o>(</span><span class=n>DateTimeFormatter</span><span class=o>.</span><span class=na>java</span><span class=o>:</span><span class=n>1720</span><span class=o>)</span>
</code></pre></td></tr></table></div></div><p>这个跟日期格式有关，这里我使用的是<code>YYMMDD</code>来格式化日期：</p><div class=highlight><div class=chroma><table class=lntable><tr><td class=lntd><pre class=chroma><code><span class=lnt>1
</span></code></pre></td><td class=lntd><pre class=chroma><code class=language-java data-lang=java><span class=n>String</span> <span class=n>currentDate</span> <span class=o>=</span> <span class=n>DateTimeFormatter</span><span class=o>.</span><span class=na>ofPattern</span><span class=o>(</span><span class=s>&#34;yyMMDD&#34;</span><span class=o>).</span><span class=na>format</span><span class=o>(</span><span class=n>LocalDateTime</span><span class=o>.</span><span class=na>now</span><span class=o>())</span>
</code></pre></td></tr></table></div></div><p>如果当前日期是从四月的10号（闰年是四月9号）即之后的日期，就会遇到上述的异常。原因是格式化字符串中的<code>D</code>指的是一年的第几天，而这里用了两个<code>D</code>，表明天数是两位数（不足两位数会补前缀0）。如果使用了前文提及的日期，也就是说当前属于一年的100天以上的天数（即天数是3位数），与格式化指定的两位数冲突，因此抛出异常。</p><p>这里想要的是每个月的天数，应当使用<code>d</code>，而不是大写的<code>D</code>。其实关于这类格式化字符需要注意大小写的问题，比如<code>y</code>和<code>Y</code>的含义也是不一样的。</p><h2 id=jdk-8新的日期和时间api>JDK 8新的日期和时间API</h2><p>新版本的日期时间API主要分为：LocalDate、LocalTime、LocalDateTime、ZonedDateTime四个类。</p><p>其中关系如下：</p><div class=highlight><div class=chroma><table class=lntable><tr><td class=lntd><pre class=chroma><code><span class=lnt>1
</span><span class=lnt>2
</span><span class=lnt>3
</span><span class=lnt>4
</span><span class=lnt>5
</span></code></pre></td><td class=lntd><pre class=chroma><code class=language-java data-lang=java><span class=n>LocalDateTime</span> <span class=o>=</span> <span class=n>LocalDate</span> <span class=o>+</span> <span class=n>LocalTime</span>

<span class=n>ZonedDateTime</span> <span class=o>=</span> <span class=n>LocalDateTime</span> <span class=o>+</span> <span class=n>ZoneOffset</span> <span class=o>+</span> <span class=n>ZoneId</span>
<span class=c1>// ZoneId是时区id
</span><span class=c1>// ZoneOffset继承自ZoneId，表示时区对应的时间偏移量，比如东八区对比零时区的偏移量是+08:00，即快了八个小时
</span></code></pre></td></tr></table></div></div><blockquote><p>GMT，即格林尼治标准时间，也就是世界时。GMT的正午是指当太阳横穿格林尼治子午线（本初子午线）时的时间。但由于地球自转不均匀不规则，导致GMT不精确，现在已经不再作为世界标准时间使用。</p><p>UTC，即协调世界时。UTC是以原子时秒长为基础，在时刻上尽量接近于GMT的一种时间计量系统。为确保UTC与GMT相差不会超过0.9秒，在有需要的情况下会在UTC内加上正或负闰秒。UTC现在作为世界标准时间使用。</p><p>计算机中的UNIX时间戳，是以GMT/UTC时间「1970-01-01T00:00:00」为起点，到具体时间的秒数，不考虑闰秒。这么做当然是为了简化计算机对时间操作的复杂度。Java调试时经常使用到的<code>System.currentTimeMillis()</code>就是获取该时间戳对应的时间毫秒值。</p></blockquote><h3 id=本地日期api>本地日期API</h3><p>在不需要处理时区时使用：LocalDate、LocalTime、LocalDateTime，也就是获取系统默认时区的日期时间。</p><div class=highlight><div class=chroma><table class=lntable><tr><td class=lntd><pre class=chroma><code><span class=lnt> 1
</span><span class=lnt> 2
</span><span class=lnt> 3
</span><span class=lnt> 4
</span><span class=lnt> 5
</span><span class=lnt> 6
</span><span class=lnt> 7
</span><span class=lnt> 8
</span><span class=lnt> 9
</span><span class=lnt>10
</span><span class=lnt>11
</span><span class=lnt>12
</span><span class=lnt>13
</span><span class=lnt>14
</span><span class=lnt>15
</span><span class=lnt>16
</span><span class=lnt>17
</span><span class=lnt>18
</span><span class=lnt>19
</span><span class=lnt>20
</span><span class=lnt>21
</span><span class=lnt>22
</span><span class=lnt>23
</span><span class=lnt>24
</span><span class=lnt>25
</span><span class=lnt>26
</span><span class=lnt>27
</span></code></pre></td><td class=lntd><pre class=chroma><code class=language-java data-lang=java><span class=c1>// 本地日期
</span><span class=c1></span><span class=n>LocalDate</span> <span class=n>localDate</span> <span class=o>=</span> <span class=n>LocalDate</span><span class=o>.</span><span class=na>now</span><span class=o>();</span>
<span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>localDate</span><span class=o>);</span>  <span class=c1>// 2021-05-12
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>localDate</span><span class=o>.</span><span class=na>getYear</span><span class=o>());</span>  <span class=c1>// 2021
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>localDate</span><span class=o>.</span><span class=na>getMonthValue</span><span class=o>());</span>  <span class=c1>// 5
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>localDate</span><span class=o>.</span><span class=na>getDayOfMonth</span><span class=o>());</span>  <span class=c1>// 12
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>localDate</span><span class=o>.</span><span class=na>withYear</span><span class=o>(</span><span class=n>2017</span><span class=o>).</span><span class=na>withMonth</span><span class=o>(</span><span class=n>7</span><span class=o>).</span><span class=na>withDayOfMonth</span><span class=o>(</span><span class=n>1</span><span class=o>));</span>  <span class=c1>// 2017-07-01
</span><span class=c1></span>
<span class=c1>// 本地时间
</span><span class=c1></span><span class=n>LocalTime</span> <span class=n>localTime</span> <span class=o>=</span> <span class=n>LocalTime</span><span class=o>.</span><span class=na>now</span><span class=o>();</span>
<span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>localTime</span><span class=o>);</span>  <span class=c1>// 00:13:19.738
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>localTime</span><span class=o>.</span><span class=na>getHour</span><span class=o>());</span>  <span class=c1>// 0
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>localTime</span><span class=o>.</span><span class=na>plusHours</span><span class=o>(</span><span class=n>1</span><span class=o>));</span> <span class=c1>// 01:13:19.738
</span><span class=c1></span>
<span class=c1>// 本地日期时间
</span><span class=c1></span><span class=n>LocalDateTime</span> <span class=n>localDateTime</span> <span class=o>=</span> <span class=n>LocalDateTime</span><span class=o>.</span><span class=na>now</span><span class=o>();</span>
<span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>localDateTime</span><span class=o>);</span>  <span class=c1>// 2021-05-12T00:13:19.738
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>localDateTime</span><span class=o>.</span><span class=na>toLocalDate</span><span class=o>());</span>    <span class=c1>// 2021-05-12
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>localDateTime</span><span class=o>.</span><span class=na>toLocalTime</span><span class=o>());</span>    <span class=c1>// 00:13:19.738
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>localDateTime</span><span class=o>.</span><span class=na>getHour</span><span class=o>());</span>    <span class=c1>// 0
</span><span class=c1></span>
<span class=c1>// 指定日期
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>LocalDate</span><span class=o>.</span><span class=na>of</span><span class=o>(</span><span class=n>2017</span><span class=o>,</span> <span class=n>7</span><span class=o>,</span> <span class=n>1</span><span class=o>));</span>   <span class=c1>// 2017-07-01
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>LocalTime</span><span class=o>.</span><span class=na>of</span><span class=o>(</span><span class=n>0</span><span class=o>,</span> <span class=n>0</span><span class=o>));</span>     <span class=c1>// 00:00
</span><span class=c1></span>
<span class=c1>// 解析日期字符串
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>LocalTime</span><span class=o>.</span><span class=na>parse</span><span class=o>(</span><span class=s>&#34;20:15:30&#34;</span><span class=o>));</span>    <span class=c1>// 20:15:30
</span></code></pre></td></tr></table></div></div><h3 id=时区日期api>时区日期API</h3><p>时区日期类是ZonedDateTime：</p><div class=highlight><div class=chroma><table class=lntable><tr><td class=lntd><pre class=chroma><code><span class=lnt> 1
</span><span class=lnt> 2
</span><span class=lnt> 3
</span><span class=lnt> 4
</span><span class=lnt> 5
</span><span class=lnt> 6
</span><span class=lnt> 7
</span><span class=lnt> 8
</span><span class=lnt> 9
</span><span class=lnt>10
</span></code></pre></td><td class=lntd><pre class=chroma><code class=language-java data-lang=java><span class=c1>// 时区日期时间
</span><span class=c1></span><span class=n>ZonedDateTime</span> <span class=n>zonedDateTime</span> <span class=o>=</span> <span class=n>ZonedDateTime</span><span class=o>.</span><span class=na>now</span><span class=o>();</span>
<span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>zonedDateTime</span><span class=o>);</span>  <span class=c1>// 2021-05-12T08:22:21.404+08:00[Asia/Shanghai]
</span><span class=c1></span>
<span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>zonedDateTime</span><span class=o>.</span><span class=na>getYear</span><span class=o>());</span>    <span class=c1>// 2021
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>zonedDateTime</span><span class=o>.</span><span class=na>getOffset</span><span class=o>());</span>  <span class=c1>// +08:00
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>zonedDateTime</span><span class=o>.</span><span class=na>getZone</span><span class=o>());</span>    <span class=c1>// Asia/Shanghai
</span><span class=c1></span>
<span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>ZoneId</span><span class=o>.</span><span class=na>systemDefault</span><span class=o>());</span>     <span class=c1>// Asia/Shanghai
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>ZoneId</span><span class=o>.</span><span class=na>SHORT_IDS</span><span class=o>.</span><span class=na>get</span><span class=o>(</span><span class=s>&#34;CTT&#34;</span><span class=o>));</span><span class=c1>// Asia/Shanghai
</span></code></pre></td></tr></table></div></div><h3 id=日期和时区的转换>日期和时区的转换</h3><p>可以给本地日期加上时区信息，以此获取对应的时区日期。</p><p>时区日期在转换时区时可以分为两种，一种是本地日期不变，单纯改变时区；另一种是将一个时区日期转换为其他时区的日期，此时不仅会改变时区，还会改变本地日期。</p><div class=highlight><div class=chroma><table class=lntable><tr><td class=lntd><pre class=chroma><code><span class=lnt> 1
</span><span class=lnt> 2
</span><span class=lnt> 3
</span><span class=lnt> 4
</span><span class=lnt> 5
</span><span class=lnt> 6
</span><span class=lnt> 7
</span><span class=lnt> 8
</span><span class=lnt> 9
</span><span class=lnt>10
</span><span class=lnt>11
</span><span class=lnt>12
</span><span class=lnt>13
</span><span class=lnt>14
</span><span class=lnt>15
</span><span class=lnt>16
</span><span class=lnt>17
</span><span class=lnt>18
</span><span class=lnt>19
</span><span class=lnt>20
</span><span class=lnt>21
</span><span class=lnt>22
</span><span class=lnt>23
</span><span class=lnt>24
</span><span class=lnt>25
</span><span class=lnt>26
</span></code></pre></td><td class=lntd><pre class=chroma><code class=language-java data-lang=java><span class=n>LocalDate</span> <span class=n>localDate</span> <span class=o>=</span> <span class=n>LocalDate</span><span class=o>.</span><span class=na>parse</span><span class=o>(</span><span class=s>&#34;2021-01-05&#34;</span><span class=o>);</span>
<span class=c1>// LocalDate转换为LocalDateTime
</span><span class=c1></span><span class=n>LocalDateTime</span> <span class=n>localDateTime</span> <span class=o>=</span> <span class=n>LocalDateTime</span><span class=o>.</span><span class=na>of</span><span class=o>(</span><span class=n>localDate</span><span class=o>,</span> <span class=n>LocalTime</span><span class=o>.</span><span class=na>MIN</span><span class=o>);</span>
<span class=c1>// 指定为东八区时间
</span><span class=c1></span><span class=n>ZonedDateTime</span> <span class=n>zonedDateTime</span> <span class=o>=</span> <span class=n>localDateTime</span><span class=o>.</span><span class=na>atZone</span><span class=o>(</span><span class=n>ZoneId</span><span class=o>.</span><span class=na>of</span><span class=o>(</span><span class=s>&#34;UTC+08:00&#34;</span><span class=o>));</span>

<span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>localDate</span><span class=o>);</span>      <span class=c1>// 2021-01-05
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>localDateTime</span><span class=o>);</span>  <span class=c1>// 2021-01-05T00:00
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>zonedDateTime</span><span class=o>);</span>  <span class=c1>// 2021-01-05T00:00+08:00[UTC+08:00]
</span><span class=c1></span>	
<span class=c1>// 日期格式化
</span><span class=c1>// 2021-01-05T00:00:00.000Z
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>localDateTime</span><span class=o>.</span><span class=na>format</span><span class=o>(</span><span class=n>DateTimeFormatter</span><span class=o>.</span><span class=na>ofPattern</span><span class=o>(</span><span class=s>&#34;yyyy-MM-dd&#39;T&#39;HH:mm:ss.SSS&#39;Z&#39;&#34;</span><span class=o>)));</span>

<span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>zonedDateTime</span><span class=o>.</span><span class=na>toLocalDateTime</span><span class=o>());</span>    <span class=c1>// 2021-01-05T00:00
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>zonedDateTime</span><span class=o>.</span><span class=na>toOffsetDateTime</span><span class=o>());</span>   <span class=c1>// 2021-01-05T00:00+08:00
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>zonedDateTime</span><span class=o>.</span><span class=na>getOffset</span><span class=o>());</span>          <span class=c1>// +08:00
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>zonedDateTime</span><span class=o>.</span><span class=na>getZone</span><span class=o>());</span>            <span class=c1>// UTC+08:00
</span><span class=c1></span>
<span class=c1>// 换算为零时区时间
</span><span class=c1></span><span class=n>ZonedDateTime</span> <span class=n>withZoneSameInstant</span> <span class=o>=</span> <span class=n>zonedDateTime</span><span class=o>.</span><span class=na>withZoneSameInstant</span><span class=o>(</span><span class=n>ZoneId</span><span class=o>.</span><span class=na>of</span><span class=o>(</span><span class=s>&#34;Z&#34;</span><span class=o>));</span>
<span class=c1>// 单纯修改时区信息
</span><span class=c1></span><span class=n>ZonedDateTime</span> <span class=n>withZoneSameLocal</span> <span class=o>=</span> <span class=n>zonedDateTime</span><span class=o>.</span><span class=na>withZoneSameLocal</span><span class=o>(</span><span class=n>ZoneId</span><span class=o>.</span><span class=na>of</span><span class=o>(</span><span class=s>&#34;Z&#34;</span><span class=o>));</span>

<span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>withZoneSameInstant</span><span class=o>.</span><span class=na>toLocalDateTime</span><span class=o>());</span>  <span class=c1>// 2021-01-04T16:00
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>withZoneSameLocal</span><span class=o>.</span><span class=na>toLocalDateTime</span><span class=o>());</span>    <span class=c1>// 2021-01-05T00:00
</span></code></pre></td></tr></table></div></div><h3 id=javasql包下的类和新的日期类的转换><code>java.sql</code>包下的类和新的日期类的转换：</h3><div class=highlight><div class=chroma><table class=lntable><tr><td class=lntd><pre class=chroma><code><span class=lnt> 1
</span><span class=lnt> 2
</span><span class=lnt> 3
</span><span class=lnt> 4
</span><span class=lnt> 5
</span><span class=lnt> 6
</span><span class=lnt> 7
</span><span class=lnt> 8
</span><span class=lnt> 9
</span><span class=lnt>10
</span><span class=lnt>11
</span><span class=lnt>12
</span><span class=lnt>13
</span></code></pre></td><td class=lntd><pre class=chroma><code class=language-java data-lang=java><span class=c1>// 2021-05-01
</span><span class=c1></span><span class=n>LocalDate</span> <span class=n>localDate</span> <span class=o>=</span> <span class=n>LocalDate</span><span class=o>.</span><span class=na>of</span><span class=o>(</span><span class=n>2021</span><span class=o>,</span> <span class=n>5</span><span class=o>,</span> <span class=n>1</span><span class=o>);</span>
<span class=c1>// 2021-05-01
</span><span class=c1></span><span class=kd>final</span> <span class=n>Date</span> <span class=n>sqlDate</span> <span class=o>=</span> <span class=n>Date</span><span class=o>.</span><span class=na>valueOf</span><span class=o>(</span><span class=n>localDate</span><span class=o>);</span>
<span class=c1>// 2021-05-01
</span><span class=c1></span><span class=n>localDate</span> <span class=o>=</span> <span class=n>sqlDate</span><span class=o>.</span><span class=na>toLocalDate</span><span class=o>();</span>

<span class=c1>// 2021-05-01T00:16:44.032
</span><span class=c1></span><span class=n>LocalDateTime</span> <span class=n>localDateTime</span> <span class=o>=</span> <span class=n>LocalDateTime</span><span class=o>.</span><span class=na>of</span><span class=o>(</span><span class=n>localDate</span><span class=o>,</span> <span class=n>LocalTime</span><span class=o>.</span><span class=na>now</span><span class=o>());</span>
<span class=c1>// 2021-05-01 00:16:44.032
</span><span class=c1></span><span class=kd>final</span> <span class=n>Timestamp</span> <span class=n>timestamp</span> <span class=o>=</span> <span class=n>Timestamp</span><span class=o>.</span><span class=na>valueOf</span><span class=o>(</span><span class=n>localDateTime</span><span class=o>);</span>
<span class=c1>// 2021-05-01T00:16:44.032
</span><span class=c1></span><span class=n>localDateTime</span> <span class=o>=</span> <span class=n>timestamp</span><span class=o>.</span><span class=na>toLocalDateTime</span><span class=o>();</span>
</code></pre></td></tr></table></div></div><h3 id=获取月份年份的最后一天>获取月份、年份的最后一天</h3><p>JDK 8提供了<code>TemporalAdjusters</code>工具类来实现调整时间的功能：</p><div class=highlight><div class=chroma><table class=lntable><tr><td class=lntd><pre class=chroma><code><span class=lnt> 1
</span><span class=lnt> 2
</span><span class=lnt> 3
</span><span class=lnt> 4
</span><span class=lnt> 5
</span><span class=lnt> 6
</span><span class=lnt> 7
</span><span class=lnt> 8
</span><span class=lnt> 9
</span><span class=lnt>10
</span><span class=lnt>11
</span><span class=lnt>12
</span><span class=lnt>13
</span><span class=lnt>14
</span></code></pre></td><td class=lntd><pre class=chroma><code class=language-java data-lang=java><span class=c1>// 2021-07-27
</span><span class=c1></span><span class=kd>final</span> <span class=n>LocalDate</span> <span class=n>localDate</span> <span class=o>=</span> <span class=n>LocalDate</span><span class=o>.</span><span class=na>now</span><span class=o>();</span>
<span class=c1>// 2021-07-01
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>localDate</span><span class=o>.</span><span class=na>with</span><span class=o>(</span><span class=n>TemporalAdjusters</span><span class=o>.</span><span class=na>firstDayOfMonth</span><span class=o>()));</span>
<span class=c1>// 2021-01-01
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>localDate</span><span class=o>.</span><span class=na>with</span><span class=o>(</span><span class=n>TemporalAdjusters</span><span class=o>.</span><span class=na>firstDayOfYear</span><span class=o>()));</span>
<span class=c1>// 2021-08-01
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>localDate</span><span class=o>.</span><span class=na>with</span><span class=o>(</span><span class=n>TemporalAdjusters</span><span class=o>.</span><span class=na>firstDayOfNextMonth</span><span class=o>()));</span>
<span class=c1>// 2022-01-01
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>localDate</span><span class=o>.</span><span class=na>with</span><span class=o>(</span><span class=n>TemporalAdjusters</span><span class=o>.</span><span class=na>firstDayOfNextYear</span><span class=o>()));</span>
<span class=c1>// 当月第一个周一： 2021-07-05
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>localDate</span><span class=o>.</span><span class=na>with</span><span class=o>(</span><span class=n>TemporalAdjusters</span><span class=o>.</span><span class=na>firstInMonth</span><span class=o>(</span><span class=n>DayOfWeek</span><span class=o>.</span><span class=na>MONDAY</span><span class=o>)));</span>
<span class=c1>// 当月最后一个周五： 2021-07-30
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>localDate</span><span class=o>.</span><span class=na>with</span><span class=o>(</span><span class=n>TemporalAdjusters</span><span class=o>.</span><span class=na>lastInMonth</span><span class=o>(</span><span class=n>DayOfWeek</span><span class=o>.</span><span class=na>FRIDAY</span><span class=o>)));</span>
</code></pre></td></tr></table></div></div><h3 id=比较两个日期>比较两个日期</h3><div class=highlight><div class=chroma><table class=lntable><tr><td class=lntd><pre class=chroma><code><span class=lnt> 1
</span><span class=lnt> 2
</span><span class=lnt> 3
</span><span class=lnt> 4
</span><span class=lnt> 5
</span><span class=lnt> 6
</span><span class=lnt> 7
</span><span class=lnt> 8
</span><span class=lnt> 9
</span><span class=lnt>10
</span><span class=lnt>11
</span><span class=lnt>12
</span></code></pre></td><td class=lntd><pre class=chroma><code class=language-java data-lang=java><span class=kd>final</span> <span class=n>LocalDate</span> <span class=n>date1</span> <span class=o>=</span> <span class=n>LocalDate</span><span class=o>.</span><span class=na>of</span><span class=o>(</span><span class=n>2021</span><span class=o>,</span> <span class=n>5</span><span class=o>,</span> <span class=n>1</span><span class=o>);</span>
<span class=kd>final</span> <span class=n>LocalDate</span> <span class=n>date2</span> <span class=o>=</span> <span class=n>LocalDate</span><span class=o>.</span><span class=na>of</span><span class=o>(</span><span class=n>2021</span><span class=o>,</span> <span class=n>5</span><span class=o>,</span> <span class=n>2</span><span class=o>);</span>
<span class=kd>final</span> <span class=n>LocalDate</span> <span class=n>date3</span> <span class=o>=</span> <span class=n>LocalDate</span><span class=o>.</span><span class=na>of</span><span class=o>(</span><span class=n>2021</span><span class=o>,</span> <span class=n>6</span><span class=o>,</span> <span class=n>2</span><span class=o>);</span>
<span class=c1>// 1
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>Period</span><span class=o>.</span><span class=na>between</span><span class=o>(</span><span class=n>date1</span><span class=o>,</span> <span class=n>date2</span><span class=o>).</span><span class=na>getDays</span><span class=o>());</span>
<span class=c1>// 1
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>Period</span><span class=o>.</span><span class=na>between</span><span class=o>(</span><span class=n>date1</span><span class=o>,</span> <span class=n>date3</span><span class=o>).</span><span class=na>getDays</span><span class=o>());</span>

<span class=c1>// 1
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>date1</span><span class=o>.</span><span class=na>until</span><span class=o>(</span><span class=n>date2</span><span class=o>,</span> <span class=n>ChronoUnit</span><span class=o>.</span><span class=na>DAYS</span><span class=o>));</span>
<span class=c1>// 32
</span><span class=c1></span><span class=n>System</span><span class=o>.</span><span class=na>out</span><span class=o>.</span><span class=na>println</span><span class=o>(</span><span class=n>date1</span><span class=o>.</span><span class=na>until</span><span class=o>(</span><span class=n>date3</span><span class=o>,</span> <span class=n>ChronoUnit</span><span class=o>.</span><span class=na>DAYS</span><span class=o>));</span>
</code></pre></td></tr></table></div></div><p><code>Period</code>只能用来比较两个日期之间的相对时间差，比如单纯比较年份、月份或者天数之间的相对差额，在比较的时候不会计算其他的时间单位，因此在比较<code>2021-05-01</code>和<code>2021-06-02</code>的天数差是1天，而不是32天。</p><p>如果想要比较完整的天数差，需要用<code>until()</code>方法，要用日期更小的那个来调用这个方法，否则会得到负数结果。另外这个<code>until()</code>方法有两个，要使用带有时间单位的那个方法，如果不指定时间单位，返回值是<code>Period</code>，这样就变成<code>Period</code>一样的用法了。</p><h2 id=参考链接>参考链接</h2><ul><li><a href=https://blog.csdn.net/weixin_42619772/article/details/111053743 target=_blank rel="noopener noreffer">Java YYYY/MM/dd遇到跨年日期的问题</a></li><li><a href=https://blog.csdn.net/singwhatiwanna/article/details/103966585 target=_blank rel="noopener noreffer">YYYY-MM-DD 的黑锅，我们不背！</a></li><li><a href=https://zhuanlan.zhihu.com/p/149302250 target=_blank rel="noopener noreffer">Java日期时间API系列19&ndash;Jdk8，ZonedDateTime和时区转换。</a></li><li><a href=https://blog.csdn.net/qq_40598321/article/details/112191964 target=_blank rel="noopener noreffer">【java8中的时间操作】java8中获取月的最后一天或者总天数，JDK8 LocalDate AP</a></li><li><a href=https://blog.csdn.net/weixin_31954813/article/details/113086552 target=_blank rel="noopener noreffer">localdate 比较两个时间_Java 8中处理日期和时间示例</a></li><li><a href=https://blog.csdn.net/l2580258/article/details/103845730 target=_blank rel="noopener noreffer">日期格式‘YYYY-MM-DD’中的BUG</a></li></ul><div class="details admonition note open"><div class="details-summary admonition-title"><i class="icon fas fa-pencil-alt fa-fwnote"></i>注意<i class="details-icon fas fa-angle-right fa-fw"></i></div><div class=details-content><div class=admonition-content>本文最后更新于 <span class=timeago datetime=2021-10-11T23:43:02 title="October 11, 2021">October 11, 2021</span>，文中内容可能已过时，请谨慎使用。</div></div></div><div class=post-reward><input type=checkbox name=reward id=reward hidden>
<label class=reward-button for=reward>赞赏支持</label><div class=qr-code><label class=qr-code-image for=reward><img class=image src=https://cdn.jsdelivr.net/gh/lewky/lewky.github.io@master/images/common/wechat.png>
<span>微信打赏</span></label>
<label class=qr-code-image for=reward><img class=image src=https://cdn.jsdelivr.net/gh/lewky/lewky.github.io@master/images/common/alipay.png>
<span>支付宝打赏</span></label></div></div></div><div class=post-footer id=post-footer><div class=post-info><div class=post-info-line><div class=post-info-mod><span>更新于 2021-10-11</span></div><div class=post-info-license><span><a rel="license external nofollow noopener noreffer" href=https://creativecommons.org/licenses/by-nc/4.0/ target=_blank>CC BY-NC 4.0</a></span></div></div><div class=post-info-line><div class=post-info-md><span><a class=link-to-markdown href=/posts/java-date-issues.html/index.md target=_blank>阅读原始文档</a></span></div><div class=post-info-share><span><a href=javascript:void(0); title="分享到 Twitter" data-sharer=twitter data-url=https://lewky.cn/posts/java-date-issues.html/ data-title=Java日期问题汇总 data-hashtags=Java,工作记录><i class="fab fa-twitter fa-fw"></i></a><a href=javascript:void(0); title="分享到 Facebook" data-sharer=facebook data-url=https://lewky.cn/posts/java-date-issues.html/ data-hashtag=Java><i class="fab fa-facebook-square fa-fw"></i></a><a href=javascript:void(0); title="分享到 Hacker News" data-sharer=hackernews data-url=https://lewky.cn/posts/java-date-issues.html/ data-title=Java日期问题汇总><i class="fab fa-hacker-news fa-fw"></i></a><a href=javascript:void(0); title="分享到 Line" data-sharer=line data-url=https://lewky.cn/posts/java-date-issues.html/ data-title=Java日期问题汇总><i data-svg-src=https://cdn.jsdelivr.net/npm/simple-icons@2.14.0/icons/line.svg></i></a><a href=javascript:void(0); title="分享到 微博" data-sharer=weibo data-url=https://lewky.cn/posts/java-date-issues.html/ data-title=Java日期问题汇总><i class="fab fa-weibo fa-fw"></i></a></span></div></div></div><div class=post-info-more><section class=post-tags><i class="fas fa-tags fa-fw"></i>&nbsp;<a href=/tags/java/>Java</a>,&nbsp;<a href=/tags/%E5%B7%A5%E4%BD%9C%E8%AE%B0%E5%BD%95/>工作记录</a></section><section><span><a href=javascript:void(0); onclick=window.history.back();>返回</a></span>&nbsp;|&nbsp;<span><a href=/>主页</a></span></section></div><div class=post-nav><a href=/friends/ class=prev rel=prev title=友链墙><i class="fas fa-angle-left fa-fw"></i>友链墙</a>
<a href=/posts/remote-desktop-issue.html/ class=next rel=next title=远程桌面无法复制粘贴>远程桌面无法复制粘贴<i class="fas fa-angle-right fa-fw"></i></a></div></div><div id=comments><div id=waline></div><script src=https://cdn.jsdelivr.net/npm/@waline/client/dist/Waline.min.js></script><script>new Waline({el:'#waline',meta:["nick","mail","link"],requiredMeta:["nick","mail"],login:"force",placeholder:"为防恶意灌水攻击，评论前需注册并登录，望见谅~",serverURL:"https://comment.lewky.cn/",avatarCDN:"https://sdn.geekzu.org/avatar/",pageSize:20,avatar:"retro",lang:"zh-CN",visitor:true,highlight:true,uploadImage:false,emoji:['https:\/\/cdn.jsdelivr.net\/gh\/lewky\/lewky.github.io@master/images/emoji/嘉然今天吃什么','https:\/\/cdn.jsdelivr.net\/gh\/lewky\/lewky.github.io@master/images/emoji/大航海嘉然','https:\/\/cdn.jsdelivr.net\/gh\/lewky\/lewky.github.io@master/images/emoji/向晚大魔王','https:\/\/cdn.jsdelivr.net\/gh\/lewky\/lewky.github.io@master/images/emoji/贝拉kira','https:\/\/cdn.jsdelivr.net\/gh\/lewky\/lewky.github.io@master/images/emoji/珈乐Carol','https:\/\/cdn.jsdelivr.net\/gh\/lewky\/lewky.github.io@master/images/emoji/乃琳Queen','https:\/\/cdn.jsdelivr.net\/gh\/lewky\/lewky.github.io@master/images/emoji/EveOneCat','https://cdn.jsdelivr.net/gh/walinejs/emojis@1.0.0/weibo','https:\/\/cdn.jsdelivr.net\/gh\/lewky\/lewky.github.io@master/images/emoji/滑稽','https:\/\/cdn.jsdelivr.net\/gh\/lewky\/lewky.github.io@master/images/emoji/default']});</script></div></article></div></main><footer class=footer><div class=footer-container><div class=footer-line><span id=run-time></span>|
<a href=http://rssblog.vercel.app/ target=_blank rel=noopener title=RSSBlog><i class="fas fa-fw fa-inbox"></i>&nbsp;RSSBlog</a></div><div class=footer-line><i class="far fa-copyright fa-fw"></i><span itemprop=copyrightYear>2018 - 2022</span><span class=author itemprop=copyrightHolder>&nbsp;<a href=/ target=_blank>雨临Lewis</a></span>&nbsp;|&nbsp;<span class=license><a rel="license external nofollow noopener noreffer" href=https://creativecommons.org/licenses/by-nc/4.0/ target=_blank>CC BY-NC 4.0</a></span><span class=icp-splitter>&nbsp;|&nbsp;</span><br class=icp-br><span class=icp><a target=_blank href=http://www.beian.miit.gov.cn/ style=font-weight:700>粤ICP备19103822</a></span></div></div></footer></div><div id=fixed-buttons><a href=# id=back-to-top class=fixed-button title=回到顶部><i class="fas fa-arrow-up fa-fw"></i></a><a href=# id=view-comments class=fixed-button title=查看评论><i class="fas fa-comment fa-fw"></i></a></div><div class=sidebar_wo><div id=leimu><img src=https://cdn.jsdelivr.net/gh/lewky/lewky.github.io@master/images/b2t/leimuA.png alt=雷姆 onmouseover="this.src='https:\/\/cdn.jsdelivr.net\/gh\/lewky\/lewky.github.io@master/images/b2t/leimuB.png'" onmouseout="this.src='https:\/\/cdn.jsdelivr.net\/gh\/lewky\/lewky.github.io@master/images/b2t/leimuA.png'" title=回到顶部></div><div class=sidebar_wo id=lamu><img src=https://cdn.jsdelivr.net/gh/lewky/lewky.github.io@master/images/b2t/lamuA.png alt=雷姆 onmouseover="this.src='https:\/\/cdn.jsdelivr.net\/gh\/lewky\/lewky.github.io@master/images/b2t/lamuB.png'" onmouseout="this.src='https:\/\/cdn.jsdelivr.net\/gh\/lewky\/lewky.github.io@master/images/b2t/lamuA.png'" title=回到底部></div></div><link rel=stylesheet href=https://cdn.jsdelivr.net/npm/lightgallery.js@1.2.0/dist/css/lightgallery.min.css><script type=text/javascript src=https://cdn.jsdelivr.net/npm/smooth-scroll@16.1.3/dist/smooth-scroll.min.js></script><script type=text/javascript src=https://cdn.jsdelivr.net/npm/lazysizes@5.2.2/lazysizes.min.js></script><script type=text/javascript src=https://cdn.jsdelivr.net/npm/lightgallery.js@1.2.0/dist/js/lightgallery.min.js></script><script type=text/javascript src=https://cdn.jsdelivr.net/npm/lg-thumbnail.js@1.2.0/dist/lg-thumbnail.min.js></script><script type=text/javascript src=https://cdn.jsdelivr.net/npm/lg-zoom.js@1.2.0/dist/lg-zoom.min.js></script><script type=text/javascript src=https://cdn.jsdelivr.net/npm/clipboard@2.0.6/dist/clipboard.min.js></script><script type=text/javascript src=https://cdn.jsdelivr.net/npm/sharer.js@0.4.0/sharer.min.js></script><script type=text/javascript>window.config={"code":{"copyTitle":"复制到剪贴板","maxShownLines":30},"comment":{},"lightGallery":{"actualSize":false,"exThumbImage":"data-thumbnail","hideBarsDelay":2000,"selector":".lightgallery","speed":400,"thumbContHeight":80,"thumbWidth":80,"thumbnail":true}};</script><script type=text/javascript src=/js/theme.min.js></script><script type=text/javascript src=https://cdn.jsdelivr.net/npm/jquery@2.1.3/dist/jquery.min.js></script><script type=text/javascript src=https://cdn.jsdelivr.net/npm/jquery-backstretch@2.1.18/jquery.backstretch.min.js></script><script>var $cdnPrefix="https://cdn.jsdelivr.net/gh/lewky/lewky.github.io@master";</script><script type=text/javascript src=/js/custom.js></script><script>var _hmt=_hmt||[];(function(){var hm=document.createElement("script");hm.src="https://hm.baidu.com/hm.js?6f278ed0fdb01edb3b1e7398379e5432";var s=document.getElementsByTagName("script")[0];s.parentNode.insertBefore(hm,s);})();</script></body></html>